<template>
    <a-modal :title="formRelation.title" :width="1400" :confirmLoading="submitLoading" :visible="formRelation.visible" :footer="null" @cancel="close">
        <a-card title="上传文件不得修改模版、上传条数不超过1000条" style="margin-bottom: 30px;">
            <template #extra> <a-button icon="download" @click="downTaskTemp" type="primary">下载模版</a-button></template>
            <input v-show="false" ref="fileRef" type="file" @change="fileChange">
            <a-button icon="upload" :disabled="initBtn" @click="$refs.fileRef.click()">导入接包人员</a-button>
            <p v-if="formRelation.fileName" style="margin-top:15px;margin-bottom:0;"><a-icon type="paper-clip" style="margin-right: 10px;"></a-icon>{{formRelation.fileName}}</p>
        </a-card>
        <a-alert
            v-if="noMsg"
            style="margin-bottom: 10px;"
            type="error"
            show-icon
            closable>
            <template #message>
                <label>《{{noMsg}}》还未开户，请尽快开户，否则影响结算发放！创建接包人员不影响。</label>
            </template>
        </a-alert>
        <a-alert message="友情提醒" description="所有人员三要素验证成功才能查询董监高、及提交人员名单" closable type="info" />
        <a-card title="人员三要素验证" style="margin-bottom: 30px;margin-top:20px">
            <template #extra>
                 <a-popconfirm
                    title="确定清空现有列表数据？数据清空后不能恢复?"
                    ok-text="确认"
                    cancel-text="取消"
                    @confirm="clearAllUser" >
                    <a-button type="danger" style="margin-right:10px;" :disabled="table.loadData.length === 0" icon="usergroup-delete">清空列表数据</a-button>
                </a-popconfirm>
                
                <a-button type="danger" icon="usergroup-add" :loading="loading" :disabled="errorBtn" @click="exportAllUser">导出失败数据</a-button>
                <a-button type="danger" icon="user-delete" :disabled="errorBtn" @click="delAllUser">删除失败数据</a-button>
                <a-button type="primary" icon="safety-certificate" :disabled="djgBtn" @click="verifiedDJG">查询董监高</a-button>
            </template>
            <a-row :gutter="24">
                <a-col :xl="8" :style="{ marginBottom: '24px' }">
                    <chart-card title="导入名单笔数" :total="total.totalCount">
                        <a-button slot="action" type="primary" @click="queryTable('')"  shape="circle" icon="search"></a-button>
                    </chart-card>
                </a-col>
                <a-col :xl="8" :style="{ marginBottom: '24px' }">
                    <chart-card title="正确名单笔数" :total="total.successCount">
                        <a-button slot="action" @click="queryTable(1)" type="primary" shape="circle" icon="search"></a-button>
                    </chart-card>
                </a-col>
                <a-col :xl="8" :style="{ marginBottom: '24px' }">
                    <chart-card title="错误名单笔数" :total="total.errorCount">
                         <a-button slot="action" @click="queryTable(2)" type="primary" shape="circle" icon="search"></a-button>
                    </chart-card>
                </a-col>
            </a-row>
            <a-table :columns="table.columns" :key="table.keys" :pagination="table.pagination" @change="handleTableChange" rowKey="id" :data-source="table.loadData">
                <template slot="action" slot-scope="text, record">
                    <template v-if="record.verifiedStatus !== 1">
                        <a v-if="!record.editable" @click="editUser(record.id)">修改</a>
                        <template v-if="record.editable">
                            <a v-if="record.editable" @click="saveUser(record)">保存</a>
                        </template>
                         <a-divider type="vertical" />
                    </template>
                    <a-popconfirm
                        title="删除后不能恢复，确认删除?"
                        ok-text="确认"
                        cancel-text="取消"
                        @confirm="delUser(record)" >
                        <a>删除</a>
                    </a-popconfirm>
                    <template v-if="record.verifiedStatus == 2">
                        <a-divider type="vertical" />
                        <a-popconfirm
                        :title="`人工验证（${record.userName}），是否验证通过！`"
                        ok-text="通过"
                        cancel-text="取消"
                        @confirm="apply(record)">
                            <a>审核</a>
                        </a-popconfirm>
                    </template>

                </template>
                <template slot="userName" slot-scope="text, record">
                    <a-input
                     v-if="record.editable" 
                     style="width: 100px;"
                     :value="text"
                     @change="e => handleChange(e.target.value, record.id, 'userName')"
                     />
                    <template v-else>{{ text }}</template>
                </template>
                <template slot="phone" slot-scope="text, record">
                    <a-input v-if="record.editable" :value="text"
                    @change="e => handleChange(e.target.value, record.id, 'phone')"/>
                    <template v-else>{{ text }}</template>
                </template>
                <template slot="bankCard" slot-scope="text, record">
                    <a-input v-if="record.editable" :value="text"
                    @change="e => handleChange(e.target.value, record.id, 'bankCard')"/>
                    <template v-else>{{ text }}</template>
                </template>
                <template slot="idCard" slot-scope="text, record">
                    <a-input v-if="record.editable" :value="text"
                    @change="e => handleChange(e.target.value, record.id, 'idCard')"/>
                    <template v-else>{{ text }}</template>
                </template>
                <template slot="settleAmount" slot-scope="text, record">
                    <a-input v-if="record.editable" :value="text"
                    @change="e => handleChange(e.target.value, record.id, 'settleAmount')"/>
                    <template v-else>{{ text }}</template>
                </template>
            </a-table>
        </a-card>
        <div class="custom-drawer-footer">
            <a-button @click="close">取消</a-button>
            <a-button type="primary" :disabled="total.errorCount !== 0 || table.loadData.length ===0" @click="submitTaskTemp">提交人员名单</a-button>
        </div>
    </a-modal>
</template>
<script>
import { mapGetters } from 'vuex'
import store from '@/store'
 import { ChartCard } from '@/components'
import { 
    allImportTaskSttleUser,
    allQueryImportTaskUserList,
    allEditImportTaskSttleUser,
    allClearTaskSttleUser,
    allDelImportTaskSttleUser,
    allQueryImportTaskUserDJG,
    allTaskSttleUserSubmit,
    settleErrorUserApply
} from '@/api/manage/sttle'
import {taskDelFailUser} from '@/api/manage/task'
import { 
    checkBankno,
    checkIDCard,
    checkPhone,
    checkAmount 
} from '@/utils/util'
import {
    COLUMNS_TASK_ONLINE
} from './form'
export default {
    name: 'taskOnline',
    components: {
        ChartCard
    },
    data () {
        return {
            formRelation:{
                title:'接包人员',
                fileName:'',
                visible:false
            },
            table:{
                columns:COLUMNS_TASK_ONLINE,
                loadData:[],
                keys:0,
                pagination:{
                    pageNum:1,
                    total:0,
                    pageSize: 5,
                    showSizeChanger: true,
					showQuickJumper: true,
                    pageSizeOptions: ["10", "20", "50", "100"],
                    showTotal: total => `共有 ${total} 条数据`,
                }
            },
            total:{
                errorCount:0,
                successCount:0,
                totalCount:0,
                djgCompleteCount:0
            },
            loading:false,
            verifiedStatus:'',
            timeCounter:null,
            noMsg:'',
            submitLoading:false,
            djgFlag:false
        }
    },
    computed: {
        ...mapGetters(['enterAccount']),
        initBtn(){
            var flag = true;
            let count = parseInt(this.total.errorCount) + parseInt(this.total.successCount);
            if(this.total.totalCount === count){
                flag = false;
            }
        },
        djgBtn(){
            var flag = true;
            let count = parseInt(this.total.errorCount) + parseInt(this.total.successCount);
            if(this.total.totalCount === count && this.table.loadData.length !==0 && !this.djgFlag && this.total.errorCount === 0){
                flag = false;
            }
            return flag;
        },
        errorBtn(){
            var flag = true;
            let count = parseInt(this.total.errorCount) + parseInt(this.total.successCount);
            if(this.total.errorCount >= 1 && this.total.totalCount === count){
                flag = false;
            }
            return flag;
        }
    },
    methods:{
        add(item){
            let {total} = this;
            for(var key in total){
                total[key] = 0;
            }
            this.formRelation.fileName = '';
            this.djgFlag = false;
            this.table.keys++;
            this.table.loadData = [];
            this.loading = false;
            this.table.pagination.pageNum =1;
            this.table.pagination.pageSize =5;
            this.formRelation.visible = true;
            this.settime();
        },
        async downTaskTemp(){await store.dispatch('allGetTasksttleUserTemp')},
        async fileChange(e) {
            const file = e.target.files[0];
            const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
            if (!isExcel) {
                e.target.value = '';
                this.$message.error('只能上传后缀 xlsx、xls格式!');
                return
            }
            const isLt1m = file.size / 1024 / 1024 < 10;
            if (!isLt1m) {
                e.target.value = '';
                this.$message.error("文件不得大于10MB!");
                return false;
            }
            let formData = new FormData();
            formData.append("file",file);
            formData.append('taskId',this.$route.query.taskId);
            e.target.value = '';
            const {code,data} = await allImportTaskSttleUser(formData);
            if(code === '1'){
                this.$message.success('操作成功');
                this.formRelation.fileName = file.name;
                this.settime();
            }
        },
        async verifiedDJG(){
            let params = {taskId:this.$route.query.taskId}
            const {code} = await allQueryImportTaskUserDJG(params);
            if(code === '1'){
                this.djgFlag = true;
                this.settime();
            }
        },
        settime(){
            let _this = this;
            _this.loadTable();
            _this.timeCounter = setTimeout(function() {  
                _this.settime();
            },3000);  
        },
        queryTable(verifiedStatus){
            this.verifiedStatus = verifiedStatus;
            this.djgFlag = false;
            clearTimeout(this.timeCounter);
            this.table.pagination.pageSize = 5;
            this.table.pagination.pageNum = 1;
            this.loadTable();
        },
        async loadTable(){
            let params = {};
            params.taskId = this.$route.query.taskId;
            params.pageNum = this.table.pagination.pageNum;
            params.pageSize = this.table.pagination.pageSize;
            params.verifiedStatus = this.verifiedStatus;
            const {code,data,errorCount,successCount,totalCount,djgCompleteCount} = await allQueryImportTaskUserList(params);
            if(code ==='1'){
                this.table.loadData = data.content;
                this.table.loadData.forEach(v => {
                    v.editable = false;
                });
                this.table.pagination.total = data.total || 0;
                this.total.errorCount = errorCount;
                this.total.successCount = successCount;
                this.total.totalCount = totalCount;
                this.total.djgCompleteCount = djgCompleteCount;
                let count = parseInt(errorCount) + parseInt(successCount);

                if(data.content.length === 0){
                    clearTimeout(this.timeCounter);
                }

                if(this.djgFlag){
                    if(djgCompleteCount === totalCount){
                        clearTimeout(this.timeCounter);
                        this.djgFlag =false;
                    }
                }else{
                    if(totalCount === count){
                        clearTimeout(this.timeCounter);
                        this.djgFlag =false;
                    }
                }

             
            }
        },
        handleTableChange(pagination){
            this.table.pagination.pageNum = pagination.current;
            this.table.pagination.pageSize = pagination.pageSize;
            this.loadTable();
        },
         async apply(item){
            let params = {id:item.id};
            const {code} = await settleErrorUserApply(params);
            if(code === '1'){
                clearTimeout(this.timeCounter);
                this.settime();
            }
        },
        async delUser(item){
            let params = {id:item.id};
            const {code} = await allDelImportTaskSttleUser(params);
            if(code === '1'){
                clearTimeout(this.timeCounter);
                this.table.pagination.pageNum = 1;
                this.settime();
            }
        },
        async exportAllUser(){
            if(this.total.errorCount == 0){
                return this.$message.error('没有失败数据');
            }
            this.loading = true;
            let params = {taskId:this.$route.query.taskId};
            await store.dispatch('taskExprotFailUser',params);
            this.loading = false;
        },

        async clearAllUser(){
            let params = {taskId:this.$route.query.taskId};
            const {code} = await allClearTaskSttleUser(params);
            if(code==='1'){
                 this.djgFlag = false;
                 this.verifiedStatus = '';
                clearTimeout(this.timeCounter);
                this.table.pagination.pageSize = 5;
                this.table.pagination.pageNum = 1;
                this.$message.success('操作成功');
                this.loadTable();
            }
        },
        delAllUser(){
            const that = this;
            if(this.total.errorCount == 0){
                return this.$message.error('没有失败数据');
            }
            this.$confirm({
                content: '是否删除全部失败数据',
                cancelText:'关闭',
                okText:'删除',
                async onOk() {
                    let params = {taskId:that.$route.query.taskId};
                    return new Promise((resolve, reject) => {
                        const res = that.confirmOnOk(resolve, reject, params)
                        return res
                    }).catch(() =>{})
                },
                onCancel() {
                },
            })
        },
        async confirmOnOk(resolve, reject, params){
            const {code,message} = await taskDelFailUser(params);
            if(code === '1'){
                resolve()
                this.$message.success('操作成功');
                this.table.pagination.pageSize = 5;
                this.table.pagination.pageNum = 1;
                clearTimeout(this.timeCounter);
                this.settime();
            }
        },
        editUser(id){
            const newData = [...this.table.loadData];
            const target = newData.filter(item => id === item.id)[0];
            if (target) {
                target.editable = true;
                this.table.loadData = newData;
            }
        },
        handleChange(value, id, column) {
        const newData = [...this.table.loadData];
        const target = newData.filter(item => id === item.id)[0];
        if (target) {
            target[column] = value;
            this.table.loadData = newData;
        }
        },
        async saveUser(item){
            if(!checkBankno(item.bankCard)){
                return this.$message.error('银行卡输入有误！');
            }
            if(!checkIDCard(item.idCard)){
                return this.$message.error('身份证输入有误！');
            }
            if(!checkPhone(item.phone)){
                return this.$message.error('手机号输入有误！');
            }
            if(!checkAmount(item.settleAmount)){
                return this.$message.error('金额为整数、小数保留2位！');
            }

            const {code} = await allEditImportTaskSttleUser(item);
            if(code === '1'){
                this.settime();
            }
        },
        async submitTaskTemp() {
            let params = {taskId:this.$route.query.taskId};
            this.submitLoading = true;
            const {code} = await allTaskSttleUserSubmit(params);
            this.submitLoading = false;
            if(code === '1'){
                this.$message.success('操作成功');
                this.$emit("on-ok");
                this.close();
            }
        },
        close(){
        this.formRelation.visible = false;
        clearTimeout(this.timeCounter);
        }
    }
}
</script>
<style>
    .nums{
        text-align: center;
        display: block;
        padding-right: 12px;
        font-size: 20px;
    }
</style>